<?php

namespace App\Http\Controllers\Finance;

use Exception;
use Illuminate\Http\Request;
use App\Models\Finance\Field;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

/**
 * 薪资字段管理逻辑
 *
 * Date: 2018/6/4
 * @author George
 * @package App\Http\Controllers\Finance
 */
class FieldController extends Controller
{
	/**
	 * 获取公司的薪资字段信息集合
	 *
	 * Date: 2018/6/5
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		$this->validate($request, [
			'pattern_id' => 'required'
		]);
		$pattern_id = $request->get('pattern_id');
		$user = Auth::user();
		$fields = Field::query()->where([
			['company_id', '=', $user->company_id],
			['pattern_id', '=', $pattern_id],
		])->get();
		return success($fields);
	}

	/**
	 * 获取薪资字段详情
	 *
	 * Date: 2018/6/4
	 * @author George
	 * @param Field $field
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(Field $field)
	{
		$user = Auth::user();

		if ($field->company_id !== $user->company_id) {
			return failed('您无权访问', 403);
		}

		return success($field);
	}

	/**
	 * 创建薪资字段
	 *
	 * Date: 2018/6/4
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		$attributes = $this->validate($request, [
			'pattern_id' => 'required',
			'name' => 'required|unique:fields',
		], [
			'name.required' => '请输入字段名称',
			'name.unique' => '字段名已存在',
		]);
		$attributes['company_id'] = Auth::user()->company_id;

		$field = Field::create($attributes);
		return stored($field);
	}

	/**
	 * 更新字段设置
	 *
	 * Date: 2018/6/5
	 * @author George
	 * @param Request $request
	 * @param Field $field
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(Request $request, Field $field)
	{
		$attributes = $this->validate($request, [
			'name' => [
				'nullable',
				Rule::unique('fields')->ignore($field->id)
			],
			'salary' => 'nullable|boolean',
			'tax' => 'nullable|boolean',
		]);
		$field->update($attributes);
		return updated($field);
	}

	/**
	 * 删除字段
	 *
	 * Date: 2018/6/5
	 * @author George
	 * @param Field $field
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(Field $field)
	{
		try {
			DB::beginTransaction();
			$field->delete();
			$field->regulation()->delete();
			DB::commit();
			return deleted();
		} catch (Exception $exception) {
			DB::rollBack();
			return internalError('删除薪资字段失败');
		}
	}
}
